home *** CD-ROM | disk | FTP | other *** search
/ Visual Cafe 3 / Visual Cafe 3.ISO / Vcafe / JFC.bin / RTFParser.java < prev    next >
Text File  |  1998-06-30  |  9KB  |  324 lines

  1. /*
  2.  * @(#)RTFParser.java    1.1 97/11/14
  3.  * 
  4.  * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved.
  5.  * 
  6.  * This software is the confidential and proprietary information of Sun
  7.  * Microsystems, Inc. ("Confidential Information").  You shall not
  8.  * disclose such Confidential Information and shall use it only in
  9.  * accordance with the terms of the license agreement you entered into
  10.  * with Sun.
  11.  * 
  12.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
  13.  * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  14.  * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  15.  * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
  16.  * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
  17.  * THIS SOFTWARE OR ITS DERIVATIVES.
  18.  * 
  19.  */
  20. package com.sun.java.swing.text.rtf;
  21.  
  22. import java.io.*;
  23. import java.lang.*;
  24.  
  25. /**
  26.  * <b>RTFParser</b> is a subclass of <b>AbstractFilter</b> which understands basic RTF syntax
  27.  * and passes a stream of control words, text, and begin/end group
  28.  * indications to its subclass.
  29.  *
  30.  * Normally programmers will only use <b>RTFFilter</b>, a subclass of this class that knows what to
  31.  * do with the tokens this class parses.
  32.  *
  33.  * @see AbstractFilter
  34.  * @see RTFFilter
  35.  */
  36. abstract class RTFParser extends AbstractFilter
  37. {
  38.   /** The current RTF group nesting level. */
  39.   public int level;
  40.  
  41.   private int state;
  42.   private StringBuffer currentCharacters;
  43.   private String pendingKeyword;                // where keywords go while we
  44.                                                 // read their parameters
  45.   private int pendingCharacter;                 // for the \'xx construct
  46.  
  47.   private long binaryBytesLeft;                  // in a \bin blob?
  48.   ByteArrayOutputStream binaryBuf;
  49.   private boolean[] savedSpecials;
  50.  
  51.   /** A stream to which to write warnings and debugging information 
  52.    *  while parsing. This is set to <code>System.out</code> to log
  53.    *  any anomalous information to stdout. */
  54.   protected PrintStream warnings;
  55.  
  56.   // value for the 'state' variable
  57.   private final int S_text = 0;          // reading random text
  58.   private final int S_backslashed = 1;   // read a backslash, wating for next
  59.   private final int S_token = 2;         // reading a multicharacter token
  60.   private final int S_parameter = 3;     // reading a token's parameter
  61.  
  62.   private final int S_aftertick = 4;     // after reading \'
  63.   private final int S_aftertickc = 5;    // after reading \'x
  64.  
  65.   private final int S_inblob = 6;        // in a \bin blob
  66.  
  67.   /** Implemented by subclasses to interpret a paramater-less RTF keyword.
  68.    *  The keyword is passed without the leading '/' or any delimiting 
  69.    *  whitespace. */
  70.   public abstract boolean handleKeyword(String keyword);
  71.   /** Implemented by subclasses to interpret a keyword with a parameter.
  72.    *  @param keyword   The keyword, as with <code>handleKeyword(String)</code>.
  73.    *  @param parameter The parameter following the keyword. */
  74.   public abstract boolean handleKeyword(String keyword, int parameter);
  75.   /** Implemented by subclasses to interpret text from the RTF stream. */
  76.   public abstract void handleText(String text);
  77.   public void handleText(char ch) 
  78.   { handleText(String.valueOf(ch)); }
  79.   /** Implemented by subclasses to handle the contents of the \bin keyword. */
  80.   public abstract void handleBinaryBlob(byte[] data);
  81.   /** Implemented by subclasses to react to an increase
  82.    *  in the nesting level. */
  83.   public abstract void begingroup();
  84.   /** Implemented by subclasses to react to the end of a group. */
  85.   public abstract void endgroup();
  86.  
  87.   // table of non-text characters in rtf
  88.   static final boolean rtfSpecialsTable[];
  89.   static {
  90.     rtfSpecialsTable = (boolean[])noSpecialsTable.clone();
  91.     rtfSpecialsTable['\n'] = true;
  92.     rtfSpecialsTable['\r'] = true;
  93.     rtfSpecialsTable['{'] = true;
  94.     rtfSpecialsTable['}'] = true;
  95.     rtfSpecialsTable['\\'] = true;
  96.   }
  97.  
  98.   public RTFParser()
  99.   {
  100.     currentCharacters = new StringBuffer();
  101.     state = S_text;
  102.     pendingKeyword = null;
  103.     level = 0;
  104.     warnings = System.out;
  105.  
  106.     specialsTable = rtfSpecialsTable;
  107.   }
  108.  
  109.   // TODO: Handle wrapup at end of file correctly.
  110.  
  111.   public void writeSpecial(int b)
  112.     throws IOException
  113.   {
  114.     write((char)b);
  115.   }
  116.  
  117.   public void write(String s)
  118.     throws IOException
  119.   {
  120.     if (state != S_text) {
  121.       int index = 0;
  122.       int length = s.length();
  123.       while(index < length && state != S_text) {
  124.     write(s.charAt(index));
  125.     index ++;
  126.       }
  127.       
  128.       if(index >= length)
  129.     return;
  130.  
  131.       s = s.substring(index);
  132.     }
  133.  
  134.     if (currentCharacters.length() > 0)
  135.       currentCharacters.append(s);
  136.     else
  137.       handleText(s);
  138.   }
  139.  
  140.   public void write(char ch) 
  141.     throws IOException
  142.   {
  143.     boolean ok;
  144.  
  145.     switch (state)
  146.     {
  147.       case S_text:
  148.         if (ch == '\n' || ch == '\r') {
  149.       break;  // unadorned newlines are ignored
  150.     } else if (ch == '{') {
  151.       if (currentCharacters.length() > 0) {
  152.         handleText(currentCharacters.toString());
  153.         currentCharacters = new StringBuffer();
  154.       }
  155.       level ++;
  156.       begingroup();
  157.     } else if(ch == '}') {
  158.       if (currentCharacters.length() > 0) {
  159.         handleText(currentCharacters.toString());
  160.         currentCharacters = new StringBuffer();
  161.       }
  162.       if (level == 0)
  163.         throw new IOException("Too many close-groups in RTF text");
  164.           endgroup();
  165.       level --;
  166.     } else if(ch == '\\') {
  167.       if (currentCharacters.length() > 0) {
  168.         handleText(currentCharacters.toString());
  169.         currentCharacters = new StringBuffer();
  170.       }
  171.       state = S_backslashed;
  172.     } else {
  173.       currentCharacters.append(ch);
  174.     }
  175.     break;
  176.       case S_backslashed:
  177.     if (ch == '\'') {
  178.       state = S_aftertick;
  179.       break;
  180.     }
  181.     if (!Character.isLetter(ch)) {
  182.       char newstring[] = new char[1];
  183.       newstring[0] = ch;
  184.       if (!handleKeyword(new String(newstring))) {
  185.         warnings.println("Unknown keyword: " + newstring + " (" + (byte)ch + ")");
  186.       }
  187.       state = S_text;
  188.       pendingKeyword = null;
  189.       /* currentCharacters is already an empty stringBuffer */
  190.       break;
  191.     }
  192.     
  193.     state = S_token;
  194.     /* FALL THROUGH */
  195.       case S_token:
  196.     if (Character.isLetter(ch)) {
  197.       currentCharacters.append(ch);
  198.     } else {
  199.       pendingKeyword = currentCharacters.toString();
  200.       currentCharacters = new StringBuffer();
  201.       
  202.       // Parameter following?
  203.       if (Character.isDigit(ch) || (ch == '-')) {
  204.         state = S_parameter;
  205.         currentCharacters.append(ch);
  206.       } else {
  207.         ok = handleKeyword(pendingKeyword);
  208.         if (!ok)
  209.           warnings.println("Unknown keyword: " + pendingKeyword);
  210.         pendingKeyword = null;
  211.         state = S_text;
  212.  
  213.         // Non-space delimiters get included in the text
  214.         if (!Character.isWhitespace(ch))
  215.           write(ch);
  216.       }
  217.     }
  218.     break;
  219.       case S_parameter:
  220.     if (Character.isDigit(ch)) {
  221.       currentCharacters.append(ch);
  222.     } else {
  223.       /* TODO: Test correct behavior of \bin keyword */
  224.       if (pendingKeyword.equals("bin")) {  /* magic layer-breaking kwd */
  225.         long parameter = Long.parseLong(currentCharacters.toString());
  226.         pendingKeyword = null;
  227.         state = S_inblob;
  228.         binaryBytesLeft = parameter;
  229.         if (binaryBytesLeft > Integer.MAX_VALUE)
  230.         binaryBuf = new ByteArrayOutputStream(Integer.MAX_VALUE);
  231.         else
  232.         binaryBuf = new ByteArrayOutputStream((int)binaryBytesLeft);
  233.         savedSpecials = specialsTable;
  234.         specialsTable = allSpecialsTable;
  235.         break;
  236.       }
  237.           
  238.       int parameter = Integer.parseInt(currentCharacters.toString());
  239.       ok = handleKeyword(pendingKeyword, parameter);
  240.       if (!ok)
  241.         warnings.println("Unknown keyword: " + pendingKeyword +
  242.                  " (param " + currentCharacters + ")");
  243.       pendingKeyword = null;
  244.       currentCharacters = new StringBuffer();
  245.       state = S_text;
  246.  
  247.       // Delimiters here are interpreted as text too
  248.       if (!Character.isWhitespace(ch))
  249.         write(ch);
  250.     }
  251.     break;
  252.       case S_aftertick:
  253.     if (Character.digit(ch, 16) == -1)
  254.       state = S_text;
  255.     else {
  256.       pendingCharacter = Character.digit(ch, 16);
  257.       state = S_aftertickc;
  258.     }
  259.     break;
  260.       case S_aftertickc:
  261.     state = S_text;
  262.     if (Character.digit(ch, 16) != -1)
  263.     {
  264.       pendingCharacter = pendingCharacter * 16 + Character.digit(ch, 16);
  265.       ch = translationTable[pendingCharacter];
  266.       if (ch != 0)
  267.           handleText(ch);
  268.     }
  269.     break;
  270.       case S_inblob:
  271.     binaryBuf.write(ch);
  272.     binaryBytesLeft --;
  273.     if (binaryBytesLeft == 0) {
  274.         state = S_text;
  275.         specialsTable = savedSpecials;
  276.         savedSpecials = null;
  277.         handleBinaryBlob(binaryBuf.toByteArray());
  278.         binaryBuf = null;
  279.     }
  280.       }
  281.   }
  282.  
  283.   /** Flushes any buffered but not yet written characters. 
  284.    *  Subclasses which override this method should call this
  285.    *  method <em>before</em> flushing
  286.    *  any of their own buffers. */
  287.   public void flush()
  288.     throws IOException
  289.   {
  290.     super.flush();
  291.  
  292.     if (state == S_text && currentCharacters.length() > 0) {
  293.       handleText(currentCharacters.toString());
  294.       currentCharacters = new StringBuffer();
  295.     }
  296.   }
  297.  
  298.   /** Closes the parser. Currently, this simply does a <code>flush()</code>,
  299.    *  followed by some minimal consistency checks. */
  300.   public void close()
  301.     throws IOException
  302.   {
  303.     flush();
  304.  
  305.     if (state != S_text || level > 0) {
  306.       warnings.println("Truncated RTF file.");
  307.       
  308.       /* TODO: any sane way to handle termination in a non-S_text state? */
  309.       /* probably not */
  310.  
  311.       /* this will cause subclasses to behave more reasonably
  312.      some of the time */
  313.       while (level > 0) {
  314.       endgroup();
  315.       level --;
  316.       }
  317.     }
  318.  
  319.     super.close();
  320.   }
  321.  
  322. }
  323.  
  324.